<template>
  <div class="patient-detail-container">
    <!-- 顶部医生信息 -->
    <div class="doctor-info">
      <div class="avatar">
        <img src="@/assets/doctor-avatar.png" alt="医生头像" />
      </div>
      <div class="doctor-name">
        <h2>Hi! {{ userInfo.userName  }} 医生</h2>
      </div>
    </div>

    <!-- 左右布局容器 -->
    <div class="main-content">
      <!-- 左侧：患者基本信息、流量总和和生命体征 -->
      <div class="left-column">
        <!-- 患者基本信息 -->
        <div class="patient-info-card">
          <div class="basic-info">
            <div class="left-info">
              <div class="bed-info">{{ patientInfo.wardName || '12' }}床</div>
              <div class="name-info">
                {{ patientInfo.name || 'Eric' }}
                <span class="age">{{ patientInfo.age || '32' }}岁</span>
                <span class="gender-icon" v-if="patientInfo.sex === 1">♂</span>
                <span class="gender-icon" v-else-if="patientInfo.sex === 0">♀</span>
              </div>
              <div class="nurse-level">
                <span class="nurse-badge">{{ patientInfo.nurseLevel || '二级护理' }}</span>
                <span class="danger-badge" v-if="patientInfo.isDanger">病危</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 出入量总和 -->
        <div class="fluid-summary-card">
          <h3 class="fluid-title">出入量总和</h3>
          <div class="fluid-container">
            <div class="fluid-item">
              <div class="fluid-label">近24小时<br>总入量 ml</div>
              <div class="fluid-value in-value">{{ fluidInfo.totalIntake  }}</div>
            </div>
            <div class="fluid-vertical-divider"></div>
            <div class="fluid-item">
              <div class="fluid-label">近24小时<br>总出量 ml</div>
              <div class="fluid-value out-value">{{ fluidInfo.totalOutput  }}</div>
            </div>
          </div>
          
          <!-- 添加蓝色箭头按钮跳转 -->
          <div class="arrow-container">
            <div class="blue-arrow" @click="navigateToFluidDetail">
              <span class="arrow-icon">→</span>
            </div>
          </div>
        </div>

        <!-- 生命体征 -->
        <div class="vital-signs-card">
          <h3 class="vital-signs-title">护理记录</h3>
          <div class="vital-signs-container">
            <div class="vital-item">
              <div class="vital-value">{{ vitalSigns.respiration || 18 }}</div>
              <div class="vital-label">呼吸 bpm</div>
            </div>
            <div class="vital-item">
              <div class="vital-value">{{ vitalSigns.bloodPressure || '120/80' }}</div>
              <div class="vital-label">无创血压 mmHg</div>
            </div>
            <div class="vital-item">
              <div class="vital-value">{{ vitalSigns.temperature || 37.5 }}</div>
              <div class="vital-label">体温 °C</div>
            </div>
            <div class="vital-item">
              <div class="vital-value">{{ vitalSigns.pulseRate || 85 }}</div>
              <div class="vital-label">脉率 bpm</div>
            </div>
            <div class="vital-item">
              <div class="vital-value">{{ vitalSigns.bloodOxygen || 98 }}</div>
              <div class="vital-label">血氧 %</div>
            </div>
            <div class="vital-item">
              <div class="vital-value">{{ vitalSigns.heartRate || 83 }}</div>
              <div class="vital-label">心率 bpm</div>
            </div>
          </div>
          
          <!-- 添加蓝色箭头按钮跳转 -->
          <div class="arrow-container">
            <div class="blue-arrow" @click="navigateToVitalDetail">
              <span class="arrow-icon">→</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧：出入量明细 -->
      <div class="right-column">
        <!-- 出入量明细卡片 -->
        <div class="fluid-detail-card">
          <h3 class="fluid-title">出入量明细</h3>
          
          <!-- 入出量明细表格 -->
          <div class="fluid-detail">
            <div class="table-container">
              <div class="table-header">
                <div class="radio-group">
                  <label class="radio-label"><input type="radio" name="fluidType" value="input" v-model="selectedFluidType" checked> 入量明细</label>
                  <label class="radio-label"><input type="radio" name="fluidType" value="output" v-model="selectedFluidType"> 出量明细</label>
                </div>
              </div>
              
              <!-- 入量明细表格 -->
              <table v-if="selectedFluidType === 'input'" class="fluid-table">
                <thead>
                  <tr>
                    <th width="60">序号</th>
                    <th>入量名称</th>
                    <th width="80">入量值</th>
                    <th width="60">单位</th>
                    <th width="140">录入时间</th>
                    <th width="80">录入人</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(item, index) in fluidInfo.intakeDetails" :key="'intake-'+index">
                    <td>{{ index + 1 }}</td>
                    <td>{{ item.adiName }}</td>
                    <td>{{ item.inValue }}</td>
                    <td>{{ item.unit }}</td>
                    <td>{{ formatDateTime(item.adItDate) }}</td>
                    <td>{{ item.adiPeople }}</td>
                  </tr>
                </tbody>
              </table>
              
              <!-- 出量明细表格 -->
              <table v-if="selectedFluidType === 'output'" class="fluid-table">
                <thead>
                  <tr>
                    <th width="60">序号</th>
                    <th>出量名称</th>
                    <th width="80">出量值</th>
                    <th width="60">单位</th>
                    <th width="140">录入时间</th>
                    <th width="80">录入人</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(item, index) in fluidInfo.outputDetails" :key="'output-'+index">
                    <td>{{ index + 1 }}</td>
                    <td>{{ item.outputName }}</td>
                    <td>{{ item.outValue }}</td>
                    <td>{{ item.unit }}</td>
                    <td>{{ formatDateTime(item.outDate) }}</td>
                    <td>{{ item.outPeople }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>


  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import htpp from '@/api/http'
import store from '@/store'
import * as echarts from 'echarts'

// 路由和导航
const route = useRoute()
const router = useRouter()

// 图表引用
const inChart = ref(null)
const outChart = ref(null)

// 患者信息
const patientInfo = ref({
  patientCode: '',
  name: '',
  sex: 1, // 1-男, 0-女
  age: '',
  nurseLevel: '二级护理',
  isDanger: true,
  wardName: '12'
})

// 用户信息
const userInfo = ref({
  userName: '',
  userId: ''
})

// 流体信息
const fluidInfo = ref({
  totalIntake: 0, // 总入量
  totalOutput: 0, // 总出量
  intakeDetails: [], // 入量明细数据
  outputDetails: [] // 出量明细数据
})

// 生命体征
const vitalSigns = ref({
  respiration: 18,
  bloodPressure: '120/80',
  temperature: 37.5,
  pulseRate: 85,
  bloodOxygen: 98,
  heartRate: 83
})

// 选中的流体类型 (入量/出量)
const selectedFluidType = ref('input')

// 格式化日期时间
const formatDateTime = (date) => {
  if (!date) return ''
  
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 获取医生信息
const getPatientInfo = async () => {
  const patientCode = route.query.patientCode
  const patientName = route.query.patientName
  const patientAge = route.query.patientAge
  const patientSex = route.query.patientSex
  

  
  // 直接使用路由参数中的患者基本信息
  patientInfo.value = {
    patientCode,
    name: patientName || 'Eric',
    age: patientAge || '32',
    sex: patientSex !== undefined ? parseInt(patientSex) : 1,
    nurseLevel: '二级护理',
    isDanger: true,
    wardName: '12'
  }

 
}

// 获取流体信息
const getFluidInfo = () => {
  // 分别获取入量和出量数据
  getIntakeData()
  getOutputData()
}

// 获取入量数据
const getIntakeData = () => {
  const patientCode = route.query.patientCode
  if (!patientCode) return
  
  // 从后端获取入量数据
  htpp.get(`api/DoctorManageController/GetinRecord?PatientCode=${patientCode}`).then(res => {

    if (res) {
      // 直接使用后端返回的数据
      fluidInfo.value.intakeDetails = res || []
      
      // 计算总入量 - 将所有inValue相加（保持使用inValue属性）
      fluidInfo.value.totalIntake = fluidInfo.value.intakeDetails.reduce((total, item) => {
        return total + (Number(item.inValue) || 0)
      }, 0)
    } else {
      // 使用默认数据
      fluidInfo.value.intakeDetails = []
      fluidInfo.value.totalIntake = 0
    }
  }).catch(error => {
    console.error('获取入量数据失败:', error)
    
    // 发生错误时使用默认数据
    fluidInfo.value.intakeDetails = []
    fluidInfo.value.totalIntake = 0
  })
}

// 获取出量数据
const getOutputData = () => {
  const patientCode = route.query.patientCode
  if (!patientCode) return
  
  // 从后端获取出量数据
  htpp.get(`api/DoctorManageController/GetOutRecord?PatientCode=${patientCode}`).then(res => {

    if (res) {
      // 直接使用后端返回的数据
      fluidInfo.value.outputDetails = res || []
      
      // 计算总出量 - 将所有outValue相加（保持使用outValue属性）
      fluidInfo.value.totalOutput = fluidInfo.value.outputDetails.reduce((total, item) => {
        return total + (Number(item.outValue) || 0)
      }, 0)
    } else {
      // 使用默认数据
      fluidInfo.value.outputDetails = []
      fluidInfo.value.totalOutput = 0
    }
  }).catch(error => {
    console.error('获取出量数据失败:', error)
    
    // 发生错误时使用默认数据
    fluidInfo.value.outputDetails = []
    fluidInfo.value.totalOutput = 0
  })
}

// 初始化入量图表
const initInChart = (data) => {
  if (!inChart.value) return
  
  const chart = echarts.init(inChart.value)
  const colors = ['#409EFF', '#F6BD16', '#E8684A', '#6DC8EC']
  
  // 为每个数据项添加颜色
  const chartData = data.map((item, index) => ({
    ...item,
    itemStyle: { color: colors[index % colors.length] }
  }))
  
  const option = {
    series: [{
      type: 'pie',
      radius: ['0%', '75%'],
      center: ['50%', '50%'],
      label: {
        show: true,
        position: 'inside',
        formatter: '{d}%',
        color: '#fff',
        fontSize: 14,
        fontWeight: 'bold'
      },
      labelLine: {
        show: false
      },
      itemStyle: {
        borderWidth: 2,
        borderColor: '#fff'
      },
      data: chartData
    }]
  }
  
  chart.setOption(option)
}

// 初始化出量图表
const initOutChart = (data) => {
  if (!outChart.value) return
  
  const chart = echarts.init(outChart.value)
  const colors = ['#409EFF', '#E8684A', '#F6BD16', '#6DC8EC']
  
  // 为每个数据项添加颜色
  const chartData = data.map((item, index) => ({
    ...item,
    itemStyle: { color: colors[index % colors.length] }
  }))
  
  const option = {
    series: [{
      type: 'pie',
      radius: ['0%', '75%'],
      center: ['50%', '50%'],
      label: {
        show: true,
        position: 'inside',
        formatter: '{d}%',
        color: '#fff',
        fontSize: 14,
        fontWeight: 'bold'
      },
      labelLine: {
        show: false
      },
      itemStyle: {
        borderWidth: 2,
        borderColor: '#fff'
      },
      data: chartData
    }]
  }
  
  chart.setOption(option)
}

// 获取生命体征
const getVitalSigns = async () => {
  const patientCode = route.query.patientCode
  if (!patientCode) return
  
  try {
    // 调用API获取生命体征
    const response = await htpp.get(`/api/DoctorManageController/GetPatientPatientReCord? patientCode=${patientCode}`)
    
    if (response && response.result) {
      const data = response.result
      vitalSigns.value = {
        respiration: data.respiration || 18,
        bloodPressure: data.bloodPressure || '120/80',
        temperature: data.temperature || 37.5,
        pulseRate: data.pulseRate || 85,
        bloodOxygen: data.bloodOxygen || 98,
        heartRate: data.heartRate || 83
      }
    }
  } catch (error) {
    console.error('获取生命体征失败:', error)
  }
}

// 添加跳转到入出量详情页面的方法
const navigateToFluidDetail = () => {
  // 获取患者编号
  const patientCode = patientInfo.value.patientCode
  const patientName = patientInfo.value.name

  // 跳转到入出量详情页面，并传递患者编号
  router.push({
    path: '/Echared', // 您需要替换为实际的路由路径
    query: {
      patientCode: patientCode,
      patientName: patientName
      // 可以根据需要传递更多参数
    }
  })
}

// 添加跳转到生命体征详情页面的方法
const navigateToVitalDetail = () => {
  // 获取患者编号
  const patientCode = patientInfo.value.patientCode
  
  // 跳转到生命体征详情页面，并传递患者编号
  router.push({
    path: '/your-vital-detail-path', // 您需要替换为实际的路由路径
    query: {
      patientCode: patientCode
      // 可以根据需要传递更多参数
    }
  })
}

// 获取当前登录用户信息
const getCurrentUser = () => {
  const currentUser = store.getters.getUserInfo()
  if (currentUser) {
    userInfo.value = {
      userName: currentUser.userName || '糖小糖',
      userId: currentUser.userId
    }
  }
}

onMounted(() => {
  getCurrentUser()
  getPatientInfo()
  getFluidInfo()
  getVitalSigns()
  
  // 监听窗口大小变化，调整图表大小
  window.addEventListener('resize', handleResize)
})

// 处理窗口大小变化
const handleResize = () => {
  if (inChart.value) {
    const chart = echarts.getInstanceByDom(inChart.value)
    chart?.resize()
  }
  
  if (outChart.value) {
    const chart = echarts.getInstanceByDom(outChart.value)
    chart?.resize()
  }
}

// 组件卸载时移除事件监听
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.patient-detail-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  font-family: Arial, sans-serif;
  background-color: #f7f8fa;
  min-height: 100vh;
}

/* 左右布局样式 */
.main-content {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.left-column {
  flex: 0.7;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.right-column {
  flex: 2;
}

/* 医生信息样式 */
.doctor-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px 15px;
}

.avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 15px;
  border: 2px solid #e0e0e0;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.doctor-name h2 {
  font-size: 28px;
  margin: 0;
  color: #333;
  font-weight: normal;
}

/* 患者信息卡片样式 */
.patient-info-card {
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  padding: 20px 30px;
}

.basic-info {
  display: flex;
}

.left-info {
  flex: 1;
}

.bed-info {
  font-size: 42px;
  font-weight: bold;
  color: #00b0dc;
  margin-bottom: 10px;
}

.name-info {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.age {
  font-size: 22px;
  font-weight: normal;
  margin-left: 15px;
  color: #555;
}

.gender-icon {
  font-size: 24px;
  color: #1976d2;
  margin-left: 10px;
}

.nurse-level {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.nurse-badge, .danger-badge {
  padding: 5px 15px;
  border-radius: 20px;
  font-size: 18px;
}

.nurse-badge {
  background-color: #e3f2fd;
  color: #1976d2;
}

.danger-badge {
  background-color: #ffebee;
  color: #f44336;
}

/* 出入量总和卡片样式 */
.fluid-summary-card {
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  padding: 20px 30px;
}

.fluid-title {
  font-size: 20px;
  margin-bottom: 20px;
  color: #1976d2;
  font-weight: normal;
}

/* 流体信息分割线 */
.fluid-divider-line {
  height: 1px;
  background-color: #e0e0e0;
  margin: 15px 0 25px;
}

/* 流体信息样式 */
.fluid-container {
  display: flex;
  justify-content: space-around;
  margin-top: 10px;
  margin-bottom: 25px;
}

.fluid-item {
  text-align: center;
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.fluid-label {
  font-size: 18px;
  color: #666;
  margin-bottom: 15px;
  text-align: center;
  line-height: 1.4;
}

.fluid-value {
  font-size: 54px;
  font-weight: bold;
}

.in-value {
  color: #1976d2;
}

.out-value {
  color: #f57c00;
}

.fluid-vertical-divider {
  width: 1px;
  background-color: #e0e0e0;
  margin: 0 20px;
}

/* 出入量明细卡片样式 */
.fluid-detail-card {
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  padding: 20px 30px;
}

.fluid-detail {
  margin-top: 15px;
}

.table-container {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #eaeaea;
}

.table-header {
  padding: 15px 20px;
  background-color: #f9f9f9;
  border-bottom: 1px solid #eee;
}

.radio-group {
  display: flex;
  gap: 30px;
}

.radio-label {
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 16px;
  color: #444;
}

.radio-label input {
  margin-right: 8px;
  width: 18px;
  height: 18px;
}

.fluid-table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
}

.fluid-table th, .fluid-table td {
  padding: 12px 10px;
  text-align: left;
  border-bottom: 1px solid #eee;
  font-size: 15px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.fluid-table th:nth-child(1), .fluid-table td:nth-child(1) {
  width: 60px;
}

.fluid-table th:nth-child(3), .fluid-table td:nth-child(3) {
  width: 80px;
}

.fluid-table th:nth-child(4), .fluid-table td:nth-child(4) {
  width: 60px;
}

.fluid-table th:nth-child(5), .fluid-table td:nth-child(5) {
  width: 140px;
}

.fluid-table th:nth-child(6), .fluid-table td:nth-child(6) {
  width: 80px;
}

.fluid-table th {
  background-color: #f5f5f5;
  font-weight: bold;
  color: #555;
}

.fluid-table tr:last-child td {
  border-bottom: none;
}

.fluid-table tr:hover {
  background-color: #f9f9f9;
}

/* 生命体征卡片样式 */
.vital-signs-card {
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  padding: 20px 30px;
}

.vital-signs-title {
  font-size: 20px;
  margin-bottom: 25px;
  color: #f44336;
  font-weight: normal;
}

.vital-signs-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 30px 40px;
}

.vital-item {
  text-align: center;
  padding: 15px 10px;
}

.vital-value {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
}

.vital-label {
  font-size: 16px;
  color: #666;
}

/* 导航按钮样式 */
.navigation-buttons {
  position: fixed;
  bottom: 30px;
  right: 30px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.nav-button {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: #1976d2;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2);
  transition: all 0.3s;
  text-decoration: none;
}

.nav-button:hover {
  transform: scale(1.1);
  background-color: #1565c0;
}

.nav-icon {
  font-size: 24px;
}

/* 添加蓝色箭头按钮跳转 */
.arrow-container {
  text-align: right;
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.blue-arrow {
  display: flex;
  width: 45px;
  height: 45px;
  border-radius: 50%;
  background-color: #409EFF;
  color: white;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2);
  transition: all 0.3s;
  margin-right: 10px;
}

.blue-arrow:hover {
  transform: scale(1.1);
  background-color: #1976d2;
}

.arrow-icon {
  font-size: 26px;
}

/* 响应式布局 */
@media (max-width: 1024px) {
  .main-content {
    flex-direction: column;
  }
  
  .left-column, .right-column {
    flex: 1;
  }
  
  .vital-signs-container {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .vital-signs-container {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>
